import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  Button,
  Row,
  Col,
  Spin,
  Typography,
  App,
  Space,
  Table,
  Checkbox,
  Divider
} from 'antd';
import {
  ArrowLeftOutlined,
  SaveOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import productService from '../../services/productService';
import type {
  ProductCategory,
  ProductAttribute,
  CreateProductParams,
  AttributeValue as ServiceAttributeValue
} from '../../services/productService';
import ImageUpload from '../../components/common/ImageUpload';

const { TextArea } = Input;
const { Title } = Typography;

interface ProductVariant {
  id?: number; // 编辑时才有id
  price: number;
  stock: number;
  attValues: number[]; // 属性值ID数组
  status: number;
  attributeValues?: ServiceAttributeValue[]; // 用于显示，不传给后端
}

interface AttributesValue {
  id: number; // 属性ID
  values: number[]; // 该属性下选择的所有值ID
}

interface AttributeGroup {
  id: number;
  name: string;
  values: ServiceAttributeValue[];
}

interface ProductDetailData {
  id: number;
  type: number;
  canBuy: boolean;
  category: {
    id: number;
    name: string;
  };
  title: string;
  description: string;
  image: string;
  images: string[];
  detail?: string;
  variants?: {
    id: number;
    attributeValues: ServiceAttributeValue[];
    code: string;
    price: number;
    stock: number;
    status: number;
  }[];
  price: number;
  status: number;
  stock: number;
  sales: number;
  attributeGroups?: AttributeGroup[];
  createdAt?: string;
  updatedAt?: string;
}

const ProductDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { message } = App.useApp();
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);
  const [product, setProduct] = useState<ProductDetailData | null>(null);
  const [categories, setCategories] = useState<ProductCategory[]>([]);
  const [attributes, setAttributes] = useState<ProductAttribute[]>([]);
  const [isMultiStyle, setIsMultiStyle] = useState(false);
  const [selectedAttributes, setSelectedAttributes] = useState<number[]>([]);
  const [variants, setVariants] = useState<ProductVariant[]>([]);

  const isNewProduct = id === 'new';

  // 加载商品详情
  const loadProductDetail = async () => {
    if (isNewProduct) {
      const defaultProduct: ProductDetailData = {
        id: 0,
        title: '',
        category: { id: 0, name: '' },
        image: '',
        images: [],
        description: '',
        detail: '',
        type: 1, // 默认实体商品
        stock: 0,
        price: 0,
        status: 1,
        canBuy: true,
        sales: 0,
        variants: [],
        attributeGroups: []
      };
      setProduct(defaultProduct);
      
      // 设置表单默认值
      form.setFieldsValue({
        ...defaultProduct,
        categoryId: undefined
      });
      return;
    }
    
    setLoading(true);
    try {
      const response = await productService.getProductDetail(Number(id));
      if (response.code === 0 && response.data) {
        const productData: ProductDetailData = {
          id: response.data.id,
          type: response.data.type,
          canBuy: response.data.canBuy,
          category: response.data.category,
          title: response.data.title,
          description: response.data.description || '',
          image: response.data.image || '',
          images: response.data.images || [],
          detail: response.data.detail || '',
          variants: response.data.variants,
          price: response.data.price,
          status: response.data.status,
          stock: response.data.stock,
          sales: response.data.sales,
          attributeGroups: response.data.attributeGroups,
          createdAt: response.data.createdAt,
          updatedAt: response.data.updatedAt
        };
        setProduct(productData);
        
        // 检查是否有多款式
        const hasMultiStyle = productData.variants && productData.variants.length > 0;
        setIsMultiStyle(hasMultiStyle || false);
        
        form.setFieldsValue({
          ...productData,
          categoryId: productData.category?.id
        });

        // 设置variants数据 - 转换为我们内部使用的格式
        if (productData.variants && productData.variants.length > 0) {
          const convertedVariants = productData.variants.map(variant => ({
            id: variant.id,
            price: variant.price,
            stock: variant.stock,
            attValues: variant.attributeValues.map(attr => attr.id), // 提取属性值ID
            status: variant.status,
            attributeValues: variant.attributeValues // 用于显示
          }));
          
          setVariants(convertedVariants);
        }

        // 设置选择的属性 - 根据 attributeGroups
        if (productData.attributeGroups && productData.attributeGroups.length > 0) {
          const selectedAttrIds = productData.attributeGroups.map(group => group.id);
          setSelectedAttributes(selectedAttrIds);
        }
      } else {
        message.error(response.message || '获取商品详情失败');
      }
    } catch {
      message.error('获取商品详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载分类列表
  const loadCategories = async () => {
    try {
      const response = await productService.getCategoryList();
      if (response.code === 0 && response.data) {
        setCategories(response.data.list);
      }
    } catch {
      message.error('获取分类列表失败');
    }
  };

  // 加载属性列表
  const loadAttributes = async () => {
    try {
      const response = await productService.getAttributeList();
      if (response.code === 0 && response.data) {
        setAttributes(response.data.list);
      }
    } catch {
      message.error('获取属性列表失败');
    }
  };

  useEffect(() => {
    loadProductDetail();
    loadCategories();
    loadAttributes();
  }, [id]);

  // 生成所有可能的属性组合
  const generateVariantCombinations = (selectedAttrIds: number[]) => {
    const selectedAttrs = attributes.filter(attr => selectedAttrIds.includes(attr.id));
    
    if (selectedAttrs.length === 0) return [];

    // 获取每个属性的所有值
    const attributeValueGroups = selectedAttrs.map(attr => 
      attr.attributeValues?.map(value => ({ ...value, attributeId: attr.id })) || []
    );

    // 生成所有组合
    const combinations: ServiceAttributeValue[][] = [];
    
    const generateCombos = (index: number, currentCombo: ServiceAttributeValue[]) => {
      if (index === attributeValueGroups.length) {
        combinations.push([...currentCombo]);
        return;
      }

      for (const value of attributeValueGroups[index]) {
        currentCombo[index] = value;
        generateCombos(index + 1, currentCombo);
      }
    };

    generateCombos(0, new Array(attributeValueGroups.length));

    // 转换为ProductVariant格式
    return combinations.map((combo) => ({
      price: product?.price || 0,
      stock: 0,
      attValues: combo.map(attr => attr.id), // 属性值ID数组
      status: 1,
      attributeValues: combo // 用于显示
    }));
  };

  // 处理属性选择变化
  const handleAttributeChange = (checkedAttrIds: number[]) => {
    setSelectedAttributes(checkedAttrIds);
    const newVariants = generateVariantCombinations(checkedAttrIds);
    setVariants(newVariants);
  };

  // 处理多款式开关变化
  const handleMultiStyleChange = (checked: boolean) => {
    setIsMultiStyle(checked);
    if (!checked) {
      setSelectedAttributes([]);
      setVariants([]);
    }
  };

  // 更新变体价格
  const updateVariantPrice = (index: number, price: number) => {
    setVariants(prev => prev.map((variant, i) => 
      i === index ? { ...variant, price } : variant
    ));
  };

  // 更新变体库存
  const updateVariantStock = (index: number, stock: number) => {
    setVariants(prev => prev.map((variant, i) => 
      i === index ? { ...variant, stock } : variant
    ));
  };

  // 生成attributesValue数据
  const generateAttributesValue = (): AttributesValue[] => {
    const result: AttributesValue[] = [];
    
    selectedAttributes.forEach(attrId => {
      const attr = attributes.find(a => a.id === attrId);
      if (attr && attr.attributeValues) {
        // 收集该属性下所有被使用的值ID
        const usedValueIds = new Set<number>();
        variants.forEach(variant => {
          variant.attValues.forEach(valueId => {
            if (attr.attributeValues?.some(v => v.id === valueId)) {
              usedValueIds.add(valueId);
            }
          });
        });
        
        if (usedValueIds.size > 0) {
          result.push({
            id: attrId,
            values: Array.from(usedValueIds)
          });
        }
      }
    });
    
    return result;
  };

  // 保存商品信息
  const handleSave = async () => {
    if (!product) return;
    
    try {
      const values = await form.validateFields();
      
      // 准备variants数据 - 去除用于显示的attributeValues字段
      const submitVariants = isMultiStyle ? variants.map(variant => ({
        id: variant.id,
        price: variant.price,
        stock: variant.stock,
        attValues: variant.attValues,
        status: variant.status
      })) : undefined;
      
      const params: CreateProductParams & { 
        isMultiStyle?: boolean; 
        variants?: Omit<ProductVariant, 'attributeValues'>[]; 
        attributesValue?: AttributesValue[];
      } = {
        ...values,
        isMultiStyle,
        variants: submitVariants,
        attributesValue: isMultiStyle ? generateAttributesValue() : undefined
      };

      let response;
      if (isNewProduct) {
        response = await productService.createProduct(params as CreateProductParams);
      } else {
        response = await productService.updateProduct(Number(id), params as CreateProductParams);
      }

      if (response.code === 0) {
        message.success(isNewProduct ? '创建成功' : '保存成功');
        if (isNewProduct) {
          navigate('/products');
        } else {
          loadProductDetail();
        }
      } else {
        message.error(response.message || (isNewProduct ? '创建失败' : '保存失败'));
      }
    } catch {
      message.error(isNewProduct ? '创建失败' : '保存失败');
    }
  };

  // Variant表格列定义
  const variantColumns: ColumnsType<ProductVariant> = [
    {
      title: '属性组合',
      dataIndex: 'attributeValues',
      key: 'attributeValues',
      render: (attributeValues: ServiceAttributeValue[]) => (
        <Space wrap>
          {attributeValues?.map((attr) => {
            const attrName = attributes.find(a => a.attributeValues?.some(v => v.id === attr.id))?.name;
            return (
              <span key={attr.id}>
                {attrName}: {attr.value}
              </span>
            );
          })}
        </Space>
      )
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 150,
      render: (price: number, record, index) => (
        <InputNumber
          min={0}
          precision={2}
          value={price}
          onChange={(value) => updateVariantPrice(index, value || 0)}
          formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
        />
      )
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: 120,
      render: (stock: number, record, index) => (
        <InputNumber
          min={0}
          value={stock}
          onChange={(value) => updateVariantStock(index, value || 0)}
        />
      )
    }
  ];

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!product && !isNewProduct) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <p>商品不存在</p>
        <Button onClick={() => navigate('/products')}>返回商品列表</Button>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面头部 */}
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center', textAlign: 'left' }}>
        <Space>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={() => navigate('/products')}
          >
            返回
          </Button>
          <Title level={3} style={{ margin: 0, textAlign: 'left' }}>
            {isNewProduct ? '新建商品' : `商品详情 - ${product?.title}`}
          </Title>
        </Space>
        
        <Button type="primary" icon={<SaveOutlined />} onClick={handleSave}>
          {isNewProduct ? '创建' : '保存'}
        </Button>
      </div>

      <Form
        form={form}
        layout="vertical"
        style={{ textAlign: 'left' }}
      >
        <Row gutter={24} style={{ textAlign: 'left' }}>
          {/* 左侧：基本信息 */}
          <Col span={16}>
            <Card title="基本信息" style={{ marginBottom: 24 }}>
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label={<span style={{ textAlign: 'left', display: 'block' }}>商品名称</span>}
                    name="title"
                    rules={[{ required: true, message: '请输入商品名称' }]}
                  >
                    <Input placeholder="请输入商品名称" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label={<span style={{ textAlign: 'left', display: 'block' }}>商品分类</span>}
                    name="categoryId"
                    rules={[{ required: true, message: '请选择商品分类' }]}
                  >
                    <Select placeholder="请选择商品分类">
                      {categories.map(category => (
                        <Select.Option key={category.id} value={category.id}>
                          {category.name}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={8}>
                  <Form.Item
                    label={<span style={{ textAlign: 'left', display: 'block' }}>基础价格</span>}
                    name="price"
                    rules={[{ required: true, message: '请输入商品价格' }]}
                  >
                    <InputNumber
                      min={0}
                      precision={2}
                      style={{ width: '100%' }}
                      placeholder="请输入商品价格"
                      formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label={<span style={{ textAlign: 'left', display: 'block' }}>基础库存</span>}
                    name="stock"
                    rules={[{ required: true, message: '请输入库存数量' }]}
                  >
                    <InputNumber
                      min={0}
                      style={{ width: '100%' }}
                      placeholder="请输入库存数量"
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label={<span style={{ textAlign: 'left', display: 'block' }}>商品类型</span>}
                    name="type"
                    rules={[{ required: true, message: '请选择商品类型' }]}
                    initialValue={1}
                  >
                    <Select placeholder="请选择商品类型">
                      <Select.Option value={1}>实物商品</Select.Option>
                      <Select.Option value={2}>虚拟商品</Select.Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                label={<span style={{ textAlign: 'left', display: 'block' }}>商品描述</span>}
                name="description"
              >
                <TextArea rows={3} placeholder="请输入商品描述（选填）" />
              </Form.Item>

              <Form.Item
                label={<span style={{ textAlign: 'left', display: 'block' }}>商品详情</span>}
                name="detail"
              >
                <TextArea rows={6} placeholder="请输入商品详情（选填）" />
              </Form.Item>
            </Card>

            {/* 多款式配置 */}
            <Card title={<span style={{ textAlign: 'left' }}>款式配置</span>}>
              <div style={{ marginBottom: 16 }}>
                <Switch
                  checked={isMultiStyle}
                  onChange={handleMultiStyleChange}
                  checkedChildren="启用多款式"
                  unCheckedChildren="单款式"
                />
                <span style={{ marginLeft: 8, color: '#666' }}>
                  启用后可以为不同的属性组合设置不同的价格和库存
                </span>
              </div>

              {isMultiStyle && (
                <>
                  <Divider orientation="left">选择商品属性</Divider>
                  <div style={{ marginBottom: 16 }}>
                    <Checkbox.Group
                      value={selectedAttributes}
                      onChange={handleAttributeChange}
                    >
                      <Row>
                        {attributes.map(attr => (
                          <Col span={8} key={attr.id} style={{ marginBottom: 8 }}>
                            <Checkbox value={attr.id}>
                              {attr.name} ({attr.attributeValues?.map(v => v.value).join('、')})
                            </Checkbox>
                          </Col>
                        ))}
                      </Row>
                    </Checkbox.Group>
                  </div>

                  {variants.length > 0 && (
                    <>
                      <Divider orientation="left">设置款式价格和库存</Divider>
                      <Table
                        columns={variantColumns}
                        dataSource={variants}
                        rowKey={(record, index) => record.id ? record.id.toString() : `variant_${index}`}
                        pagination={false}
                        size="small"
                      />
                    </>
                  )}
                </>
              )}
            </Card>
          </Col>

          {/* 右侧：商品图片和状态 */}
          <Col span={8}>
            <Card title={<span style={{ textAlign: 'left' }}>商品图片</span>} style={{ marginBottom: 24 }}>
              <Form.Item label={<span style={{ textAlign: 'left', display: 'block' }}>主图</span>} name="image">
                <ImageUpload folder="okeydo/products" />
              </Form.Item>
            </Card>

            <Card title={<span style={{ textAlign: 'left' }}>商品设置</span>}>
              <Form.Item
                label={<span style={{ textAlign: 'left', display: 'block' }}>商品状态</span>}
                name="status"
                valuePropName="checked"
                getValueFromEvent={(checked) => checked ? 1 : 0}
                getValueProps={(value) => ({ checked: value === 1 })}
              >
                <Switch checkedChildren="上架" unCheckedChildren="下架" />
              </Form.Item>
              
              <Form.Item
                label={<span style={{ textAlign: 'left', display: 'block' }}>是否可购买</span>}
                name="canBuy"
                valuePropName="checked"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Card>
          </Col>
        </Row>
      </Form>
    </div>
  );
};

export default ProductDetailPage;